<?php


namespace XiaoGuai\DataStructure\Stack\SequentialStack;

use XiaoGuai\DataStructure\Stack\StackInterface;

/**
 * 栈的顺序存储表示
 * Class SequentialStack
 * @package XiaoGuai\DataStructure\StackInterface\SequentialStack
 */
class SequentialStack implements StackInterface
{
    /**
     * 栈的容量
     */
    const MAX_SIZE = 100;

    /**
     * @var array 存放栈的元素
     */
    protected $elements = [];

    /**
     * @var int|null 栈顶索引
     */
    protected $top = 0;

    /**
     * @var int|null 栈底索引
     */
    protected $bottom = 0;

    public function __construct()
    {
        $this->elements = [];
        $this->top = 0;
        $this->bottom = 0;
    }

    /**
     * 向栈中压入元素
     * @param $element
     * @return bool
     */
    public function push($element): bool
    {
        if ($this->length() >= self::MAX_SIZE) {
            return false;
        }
        $this->elements[$this->top++] = $element;
        return true;
    }

    /**
     * 从栈中弹出元素
     * @return mixed
     */
    public function pop()
    {
        if ($this->length() <= 0) {
            throw new \Exception('overflow');
        }
        return $this->elements[--$this->top];
    }

    /**
     * 返回当前栈顶元素
     * @return mixed
     */
    public function top()
    {
        if ($this->length() <= 0) {
            throw new \Exception('overflow');
        }
        return $this->elements[$this->top - 1];
    }

    /**
     * 栈是否为空
     * @return bool
     */
    public function isEmpty(): bool
    {
        return $this->top == $this->bottom;
    }

    /**
     * 栈当前存储的元素个数
     * @return int
     */
    public function length(): int
    {
        return $this->top - $this->bottom;
    }
}